package com.audaque.springboot.foshanupload.web.servletdemo.controller;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;

/**
 * @author zgb
 * @desc ...
 * @date 2023-07-20 15:25:29
 */
@WebServlet(urlPatterns = "/async",asyncSupported = true)
public class AsyncServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        long start = System.currentTimeMillis();
        //方法开启异步上下文
        AsyncContext asyncContext = request.startAsync();
        //启动一个子线程
        CompletableFuture.runAsync(() -> {
            try {
                printLog(asyncContext,asyncContext.getRequest(),asyncContext.getResponse());
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
        System.out.println("总耗时：" + (System.currentTimeMillis() - start));
    }

    private void printLog(AsyncContext asyncContext, ServletRequest request, ServletResponse response) throws InterruptedException, IOException {
        Thread.sleep(3000);
        response.getWriter().write("ok");
        //通知异步上下文请求处理完毕
        asyncContext.complete();
    }
}
